<template>
  <div v-if="value || isEditing">
    <a-form-item :label="label" :colon="false">
      <a-date-picker
        v-if="isEditing"
        v-model:value="inputValue"
        @blur="finishEdit"
        @change="onDateChange"
        placeholder="请选择到岗时间"
        style="width: 100%"
      />
      <span v-else @click="startEdit" style="cursor: pointer;">{{ displayDate || '点击选择到岗时间' }}</span>
    </a-form-item>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'

const props = defineProps<{
  value: string
  label: string
  itemId: string
}>()

const emit = defineEmits<{
  (e: 'update', id: string, value: string): void
}>()

const isEditing = ref(false)
const inputValue = ref<Dayjs | null>(props.value ? dayjs(props.value) : null)

// 显示的日期格式
const displayDate = computed(() => {
  return inputValue.value ? inputValue.value.format('YYYY-MM-DD') : ''
})

// 开始编辑
const startEdit = () => {
  isEditing.value = true
  inputValue.value = props.value ? dayjs(props.value) : null
}

// 完成编辑
const finishEdit = () => {
  isEditing.value = false
  emit('update', props.itemId, inputValue.value?.format('YYYY-MM-DD') || '')
}

// 日期改变时触发
const onDateChange = (date: Dayjs | null, dateString: string) => {
  inputValue.value = date
  finishEdit()
}

// 监听props.value变化
watch(() => props.value, (newValue) => {
  inputValue.value = newValue ? dayjs(newValue) : null
})
</script>